package com.hyc.algorithm.list;

import com.hyc.algorithm.Node.Node;

/**
 * @projectName: DataStructure
 * @package: com.hyc.algorithm.list
 * @className: RecursiveList
 * @author: 冷环渊 doomwatcher
 * @description: TODO 递归链表,求和
 * @date: 2022/2/27 19:43
 * @version: 1.0
 */
public class RecursiveList {
    public static void main(String[] args) {

        Node node = new Node(1);
        Node node1 = new Node(2);
        Node node2 = new Node(3);
        Node node3 = new Node(4);
        Node node4 = new Node(5);

        node.next = node1;
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        printNode(node);
        System.out.println("\n" + "节点求和结果 =>" + ListSum(node));

        Node changeNode = change2(node);
        recuNode(changeNode);
    }

    //遍历打印Node
    public static void printNode(Node root) {
        if (root == null) {
            return;
        }
        Node temp = root;
        while (true) {
            System.out.print(temp.val + ",");
            if (temp.next == null) {
                break;
            }
            temp = temp.next;
        }
    }

    //    遍历求和
    public static int ListSum(Node root) {
        if (root == null) {
            return -1;
        }
        //结果存储
        int res = 0;
        Node temp = root;
        while (true) {
            res += temp.val;
            if (temp.next == null) {
                break;
            }
            temp = temp.next;
        }
        return res;
    }

    //    递归遍历链表
    public static void recuNode(Node root) {
        if (root == null) {
            return;
        }
        //递归进来的时候就输出，正序
        System.out.print(root.val + ",");
        recuNode(root.next);
        ////递归完了逐层递归出来的时候输出， 倒序
        //System.out.println(root.val);
    }

    //    反转链表
    public static Node change2(Node root) {
        Node result = null;
        if (root.next.next != null) {
            result = change2(root.next);
        } else {
            result = root.next;
        }
        root.next.next = root;
        root.next = null;
        return result;
    }

}
